﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Net;
using LitJson;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using System.Reflection;

//工具类
public class Utils
{
    /// <summary>
    /// base64 解码
    /// </summary>
    /// <returns></returns>
    public static string Decode64(string str)
    {
        byte[] bstr = Convert.FromBase64String(str);
        str = System.Text.ASCIIEncoding.Default.GetString(bstr);
        return str;
    }
    /// <summary>
    /// base64编码
    /// </summary>
    /// <returns></returns>
    public static string Encode64(string str)
    {
        //System.Text.Encoding encode = System.Text.Encoding.ASCII;//中文会显示乱码
        System.Text.Encoding encode = System.Text.Encoding.Default;
        byte[] bytedata = encode.GetBytes(str);
        str = Convert.ToBase64String(bytedata, 0, bytedata.Length);
        return str;
    }
    /// <summary>
    /// MD5加密
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string Md5(string str)
    {
        // Create a new instance of the MD5CryptoServiceProvider object.
        MD5 md5Hasher = MD5.Create();
        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hasher.ComputeHash(Encoding.GetEncoding("UTF-8").GetBytes(str));
        //  return BitConverter.ToString(data);//可以直接使用这个方法
        //  Create a new Stringbuilder to collect the bytes
        //  and create a string.
        StringBuilder sBuilder = new StringBuilder();
        // Loop through each byte of the hashed data
        // and format each one as a hexadecimal string.
        foreach (byte b in data)
        {
            //{0:X2} 大写
            sBuilder.AppendFormat("{0:x2}", b);
        }
        // Return the hexadecimal string.
        return sBuilder.ToString();
    }
    private const string M_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    public static string RijndaelEncrypt(string pString, string pKey = M_KEY)
    {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes(pKey);
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(pString);
        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = keyArray;
        rDel.Mode = CipherMode.ECB;
        rDel.Padding = PaddingMode.PKCS7;
        ICryptoTransform cTransform = rDel.CreateEncryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }

    public static String RijndaelDecrypt(string pString, string pKey = M_KEY)
    {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes(pKey);
        byte[] toEncryptArray = Convert.FromBase64String(pString);
        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = keyArray;
        rDel.Mode = CipherMode.ECB;
        rDel.Padding = PaddingMode.PKCS7;
        ICryptoTransform cTransform = rDel.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        return UTF8Encoding.UTF8.GetString(resultArray);
    }

    private const string PASSWORD_BASE = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz";

    /// <summary>  
    /// 获取某个字符出现的次数
    /// </summary>  
    /// <param name="str"></param>  
    /// <param name="pattern">正则表达式</param>  
    /// <returns></returns>  
    public static int GetCharNums(string str,string pattern)
    {
        return Regex.Matches(str, pattern).Count;
    }

    /// <summary>  
    /// 去除第一个字符，取出第一个字符之后的所有字符  
    /// </summary>  
    /// <param name="str"></param>  
    /// <returns></returns>  
    public static string DeleteFirstChar(string str)
    {
        return str.Substring(1, str.Length - 1);
    }

    /// <summary>  
    /// 删除最后结尾的一个逗号  
    /// </summary>  
    public static string DelLastComma(string str)
    {
        return str.Substring(0, str.LastIndexOf(","));
    }

    /// <summary>  
    /// 删除最后结尾的指定字符后的字符  
    /// </summary>  
    public static string DelLastChar(string str, string strchar)
    {
        return str.Substring(0, str.LastIndexOf(strchar));
    }

    /// <summary>  
    /// 截取指定字符长度  
    /// </summary>  
    /// <param name="str"></param>  
    /// <param name="strchar"></param>  
    /// <returns></returns>  
    public static string SubstringChar(string str, int length)
    {
        return str.Substring(0, length);
    }

    /// <summary>  
    /// 从指定、特殊字符开始截取  
    /// </summary>  
    /// <param name="str">http://192.168.1.41:8086/upload/customer/123456_20160315181634.jpg</param>  
    /// <param name="IndexOf">/upload</param>  
    /// <returns>/upload/customer/123456_20160315181634.jpg</returns>  
    public static string SubstringIndexOfChar(string str, string IndexOf)
    {
        //return str.Substring(str.IndexOf("/upload"));  
        return str.Substring(str.IndexOf(IndexOf) + 1);
    }

    /// <summary>  
    /// 去掉最後一個字符  
    /// </summary>  
    /// <param name="prestr"></param>  
    /// <returns></returns>  
    public static string DeleteLastChar(string prestr)
    {
        int nLen = prestr.Length;
        return prestr.Remove(nLen - 1, 1);
    }

    /// <summary>  
    /// 图片文件转Base64String  
    /// </summary>  
    /// <param name="FilePath">文件绝对路径</param>  
    /// <returns></returns>  
    public static string ImageToBase64(string FilePath)
    {
        string path = @"F:\5845.jpg";
        return Convert.ToBase64String(System.IO.File.ReadAllBytes(path));
    }

    /** 
    * 生成时间戳，标准北京时间，时区为东八区，自1970年1月1日 0点0分0秒以来的秒数 
    * @return 时间戳 
    */
    public static string GenerateTimeStamp()
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(ts.TotalSeconds).ToString();
    }

    /** 
    * 生成随机串，随机串包含字母或数字 
    * @return 随机串 
    */
    public static string GenerateNonceStr()
    {
        return Guid.NewGuid().ToString().Replace("-", "");
    }

    /// <summary>  
    /// 随机密码  
    /// </summary>  
    /// <param name="length"></param>  
    /// <returns></returns>  
    public static string RandomPassword(int length)
    {
        StringBuilder sb = new StringBuilder();
        Random rnd = new Random();
        for (int i = 0; i < length; i++)
        {
            sb.Append(PASSWORD_BASE[rnd.Next(0, PASSWORD_BASE.Length)]);
        }
        return sb.ToString();
    }

    /// <summary>  
    /// 生成随机数  
    /// </summary>  
    /// <param name="length">生成字符串长度</param>  
    /// <param name="type">1.数字+字母 2.整形 3.字符 4.许愿墙随机坐标代码</param>  
    /// <returns></returns>  
    public static string GenerateCode(int length, int type)
    {
        int number;
        char code;
        string checkCode = String.Empty;

        System.Random random = new Random();
        if (type == 1)
        {
            for (int i = 0; i < length; i++)
            {
                number = random.Next();

                if (number % 2 == 0)
                    code = (char)('0' + (char)(number % 10));
                else
                    code = (char)('A' + (char)(number % 26));

                checkCode += code.ToString();
            }
        }
        else if (type == 2)
        {
            for (int i = 0; i < length; i++)
            {
                number = random.Next();
                code = (char)('0' + (char)(number % 10));
                checkCode += code.ToString();
            }
        }
        else if (type == 3)
        {
            for (int i = 0; i < length; i++)
            {
                number = random.Next();
                code = (char)('A' + (char)(number % 26));
                checkCode += code.ToString();
            }
        }
        else if (type == 4)//许愿墙随机坐标代码  
        {
            for (int i = 0; i < length; i++)
            {
                number = random.Next(10, 450);
                checkCode = number.ToString();
            }
        }
        return checkCode;
    }

    /// <summary>  
    /// 生成随机数  
    /// </summary>  
    /// <param name="length"></param>  
    /// <returns></returns>  
    public static string BuildRandomStr(int length)
    {
        Random rand = new Random();
        int num = rand.Next();
        string str = num.ToString();
        if (str.Length > length)
        {
            str = str.Substring(0, length);
        }
        else if (str.Length < length)
        {
            int n = length - str.Length;
            while (n > 0)
            {
                str.Insert(0, "0");
                n--;
            }
        }
        return str;
    }

    /// <summary>  
    /// 现有数组中抽取1个随机数  
    /// </summary>  
    /// <returns></returns>  
    public static string ArrayRandom(long[] arr)
    {
        Random r = new Random();
        string fi1 = arr[r.Next(arr.Length)].ToString();
        return fi1;
    }


    /// <summary>  
    /// 把字符串进行URL编码  
    /// </summary>  
    /// <param name="src">原字符串</param>  
    /// <param name="srcEncoding">Encoding.UTF8</param>  
    /// <returns></returns>  
    public static string UrlEncode(string src, System.Text.Encoding encoding)
    {
        byte[] b = encoding.GetBytes(src);
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < b.Length; i++)
        {
            result.Append('%');
            result.Append(b[i].ToString("X2"));
        }
        return result.ToString();
    }


    /// <summary>  
    /// Base64String转换成byte[]  
    /// </summary>  
    /// <param name="fileBase"></param>  
    /// <returns></returns>  
    public static byte[] Base64ToByte(string base64String)
    {
        byte[] file = null;
        if (!string.IsNullOrEmpty(base64String))
        {
            file = Convert.FromBase64String(base64String);
        }
        return file;
    }

    /// <summary>  
    /// 带有“,”的字符串转成int[]  
    /// </summary>  
    /// <param name="str">1,2,3,4,5,6,8,9,10,</param>  
    /// <returns></returns>  
    public static int[] StringToIntArray(string str)
    {
        int[] intArray = null;
        if (!string.IsNullOrEmpty(str))
        {
            string newStr = str.TrimEnd(',');
            intArray = newStr.Split(',').Select(v => Convert.ToInt32(v)).ToArray();
        }
        return intArray;
    }

    /// <summary>  
    /// int[]转成String字符串  
    /// </summary>  
    /// <param name="array"></param>  
    /// <returns></returns>  
    public static string IntArrayToString(int[] array)
    {
        string result = string.Empty;
        if (array.Count() > 0)
        {
            for (int i = 0; i < array.Length; i++)
            {
                if (0 == i)
                {
                    result = array[0].ToString();
                }
                else
                {
                    result = result + "," + array[i].ToString();
                }
            }
        }
        return result;
    }

    /// <summary>  
    /// 带有“,”的字符串转成string[]  
    /// </summary>  
    /// <param name="str"></param>  
    /// <returns></returns>  
    public static string[] StringToStrArray(string str)
    {
        string[] strArray = null;
        if (!string.IsNullOrEmpty(str))
        {
            strArray = str.Split(',');
        }
        return strArray;
    }

    /// <summary>  
    /// Dictionary转成String[]数组  
    /// </summary>  
    /// <param name="str"></param>  
    /// <returns></returns>  
    public static string[] DictionaryToStrArray(Dictionary<string, string> dicArray)
    {
        string[] strArray = null;
        if (dicArray.Count > 0)
        {
            List<string> list = new List<string>();
            foreach (var item in dicArray)
            {
                list.Add(item.Value);
            }
            strArray = list.ToArray();
        }
        return strArray;
    }

    /// <summary>  
    /// 带有“,”的字符串转成Dictionary<string, string>  
    /// </summary>  
    /// <param name="str"></param>  
    /// <returns></returns>  
    public static Dictionary<string, string> StringToDictionary(string str)
    {
        Dictionary<string, string> dict = new Dictionary<string, string>();
        if (!string.IsNullOrEmpty(str))
        {
            string[] strArray = str.Split(',');
            for (int i = 0; i < strArray.Length; i++)
            {
                string value = strArray[i].ToString();
                dict.Add("pic" + i.ToString(), value);
            }
        }
        return dict;
    }

    /// <summary>  
    /// Dictionary转成String字符串  
    /// 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串  
    /// </summary>  
    /// <param name="dicArray">需要拼接的数组</param>  
    /// <returns>拼接完成以后的字符串</returns>  
    public static string DictionaryToString(Dictionary<string, string> dicArray)
    {
        StringBuilder prestr = new StringBuilder();
        if (dicArray.Count > 0)
        {
            foreach (KeyValuePair<string, string> temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }
            //去掉最後一個&字符  
            int nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);
        }
        return prestr.ToString();
    }

    /// <summary>  
    /// Dictionary转成Json  
    /// </summary>  
    /// <param name="dicArray"></param>  
    /// <returns></returns>  
    public static string DictionaryToJson(Dictionary<string, string> dicArray)
    {
        StringBuilder prestr = new StringBuilder();
        prestr.Append("[");
        if (dicArray.Count > 0)
        {
            int i = 0;
            foreach (KeyValuePair<string, string> temp in dicArray)
            {
                if (i == 0)
                {
                    prestr.Append("{\"" + temp.Key + "\":" + temp.Value + ",");
                }
                else if (i == dicArray.Count - 1)
                {
                    prestr.Append("\"" + temp.Key + "\":" + temp.Value + "}");
                }
                else
                {
                    prestr.Append("\"" + temp.Key + "\":" + temp.Value + ",");
                }
                i++;
            }
        }
        prestr.Append("]");
        return prestr.ToString();
    }


    /// <summary>  
    /// Guid[]转成String字符串  
    /// </summary>  
    /// <param name="arrParams"></param>  
    /// <returns></returns>  
    public static string ArrayToString(Guid[] arrParams)
    {
        string postStr = "";
        for (int i = 0; i < arrParams.Length; i++)
        {
            if (0 == i)
            {
                postStr = "'" + arrParams[0].ToString() + "'";
            }
            else
            {
                postStr = postStr + "," + "'" + arrParams[i].ToString() + "'";
            }
        }
        return postStr;
    }

    public static int GetNullToInt(int? id)
    {
        try
        {
            if (id == null)
                return 0;
            else
                return (int)id;
        }
        catch (Exception)
        {
            return 0;
        }
    }

    public static int GetStringToInt(string id)
    {
        try
        {
            if (string.IsNullOrEmpty(id))
                return 0;
            else
                return Convert.ToInt32(id);
        }
        catch (Exception)
        {
            return 0;
        }
    }

    public static long GetNullToLong(long id)
    {
        try
        {
            if (id == null)
                return 0;
            else
                return (long)id;
        }
        catch (Exception)
        {
            return 0;
        }
    }

    public static decimal GetNullToDecimal(decimal? id)
    {
        try
        {
            if (id == null)
                return 0;
            else
                return (decimal)id;
        }
        catch (Exception)
        {
            return 0;
        }
    }

    public static decimal GetNullToDecimal(string id)
    {
        try
        {
            if (string.IsNullOrEmpty(id))
                return 0;
            else
                return Convert.ToDecimal(id);
        }
        catch (Exception)
        {
            return 0;
        }
    }

    public static string GetNullToString(string name)
    {
        try
        {
            if (string.IsNullOrEmpty(name))
                return "";
            else
                return name;
        }
        catch (Exception)
        {
            return "";
        }
    }

    public static DateTime StringToDateTime(string time)
    {
        try
        {
            if (string.IsNullOrEmpty(time))
                return Convert.ToDateTime("1870-01-01");
            else
                return Convert.ToDateTime(time);
        }
        catch (Exception)
        {
            return Convert.ToDateTime("1870-01-01");
        }
    }

    public static string GetNullToDateTime(DateTime? date)
    {
        try
        {
            if (date.HasValue)
            {
                if (Convert.ToDateTime(date) == Convert.ToDateTime("1870-01-01"))
                    return "";
            }
        }
        catch (Exception)
        {
        }
        return "";
    }

    /// <summary>  
    ///   
    /// </summary>  
    /// <typeparam name="T"></typeparam>  
    /// <param name="data"></param>  
    /// <returns></returns>  
    public static T GetNullValue<T>(T data)
    {
        if (data == null)
            return default(T);
        return (T)data;
    }

    /// <summary>  
    /// GetNullValue调用示例  
    /// </summary>  
    public void TestGetNullValue()
    {
        string str = GetNullValue<string>("test");
        int count = GetNullValue<int>(123);
        decimal price = GetNullValue<decimal>(Convert.ToDecimal(123.45));
        decimal total = GetNullValue<decimal>(Convert.ToDecimal(null));
    }


    /// <summary>  
    /// 过滤特殊字符  
    /// </summary>  
    /// <param name="str"></param>  
    /// <returns></returns>  
    public static string DelQuota(string str)
    {
        string result = str;
        string[] strQuota = { "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?" };
        for (int i = 0; i < strQuota.Length; i++)
        {
            if (result.IndexOf(strQuota[i]) > -1)
                result = result.Replace(strQuota[i], "");
        }
        return result;
    }



    #region URL请求数据
    /// <summary>  
    /// HTTP POST方式请求数据  
    /// </summary>  
    /// <param name="url">URL.</param>  
    /// <param name="param">POST的数据</param>  
    /// <returns></returns>  
    public static string HttpPost(string url, string param)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.Accept = "*/*";
        request.Timeout = 15000;
        request.AllowAutoRedirect = false;

        StreamWriter requestStream = null;
        WebResponse response = null;
        string responseStr = null;

        try
        {
            requestStream = new StreamWriter(request.GetRequestStream());
            requestStream.Write(param);
            requestStream.Close();

            response = request.GetResponse();
            if (response != null)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            request = null;
            requestStream = null;
            response = null;
        }
        return responseStr;
    }

    /// <summary>  
    /// HTTP GET方式请求数据.  
    /// </summary>  
    /// <param name="url">URL.</param>  
    /// <returns></returns>  
    public static string HttpGet(string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "GET";
        //request.ContentType = "application/x-www-form-urlencoded";  
        request.Accept = "*/*";
        request.Timeout = 15000;
        request.AllowAutoRedirect = false;

        WebResponse response = null;
        string responseStr = null;
        try
        {
            response = request.GetResponse();
            if (response != null)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            request = null;
            response = null;
        }
        return responseStr;
    }
    #endregion

    #region 时间转换
    /// <summary>
    /// 获取当前时间戳
    /// </summary>
    /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.</param>
    /// <returns></returns>
    public static long GetTimeStamp(bool bflag = true)
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        long ret;
        if (bflag)
            ret = Convert.ToInt64(ts.TotalSeconds);
        else
            ret = Convert.ToInt64(ts.TotalMilliseconds);
        return ret;
    }

    static DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
    public static string NormalizeTimpstamp0(long timpStamp)
    {
        long unixTime = timpStamp * 10000000L;
        TimeSpan toNow = new TimeSpan(unixTime);
        DateTime dt = dtStart.Add(toNow);
        return dt.ToString("yyyy-MM-dd");
    }

    /// <summary>
    /// 时钟式倒计时
    /// </summary>
    /// <param name="second"></param>
    /// <returns></returns>
    public string GetSecondString(int second)
    {
        return string.Format("{0:D2}", second / 3600) + string.Format("{0:D2}", second % 3600 / 60) + ":" + string.Format("{0:D2}", second % 60);
    }


    /// 将Unix时间戳转换为DateTime类型时间
    /// </summary>
    /// <param name="d">double 型数字</param>
    /// <returns>DateTime</returns>
    public static System.DateTime ConvertIntDateTime(double d)
    {
        System.DateTime time = System.DateTime.MinValue;
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0));
        time = startTime.AddSeconds(d);
        return time;
    }


    /// <summary>
    /// 将c# DateTime时间格式转换为Unix时间戳格式
    /// </summary>
    /// <param name="time">时间</param>
    /// <returns>double</returns>
    public static double ConvertDateTimeInt(System.DateTime time)
    {
        double intResult = 0;
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        intResult = (time - startTime).TotalSeconds;
        return intResult;
    }

    /// <summary>
    /// 日期转换成unix时间戳
    /// </summary>
    /// <param name="dateTime"></param>
    /// <returns></returns>
    public static long DateTimeToUnixTimestamp(DateTime dateTime)
    {
        var start = new DateTime(1970, 1, 1, 0, 0, 0, dateTime.Kind);
        return Convert.ToInt64((dateTime - start).TotalSeconds);
    }

    /// <summary>
    /// unix时间戳转换成日期
    /// </summary>
    /// <param name="unixTimeStamp">时间戳（秒）</param>
    /// <returns></returns>
    public static DateTime UnixTimestampToDateTime(DateTime target, long timestamp)
    {
        DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, target.Kind);
        return start.AddSeconds(timestamp);
    }
    #endregion

    #region 文件操作
    //二进制方法：存档和读档
    public static void SaveByBin<SaveObject>(string dataPath,string filename,SaveObject saveObject)
    {
        //序列化过程（将Save对象转换为字节流）
        //创建Save对象并保存当前游戏状态
        //创建一个二进制格式化程序
        BinaryFormatter bf = new BinaryFormatter();
        //创建一个文件流
        FileStream fileStream = File.Create(dataPath + "/dataFile/" + filename);
        //用二进制格式化程序的序列化方法来序列化Save对象,参数：创建的文件流和需要序列化的对象
        bf.Serialize(fileStream, saveObject);
        //关闭流
        fileStream.Close();
    }

    public static SaveObject LoadByBin<SaveObject>(string dataPath,string filename)
    {
        string filePath = dataPath + "/dataFile/" + filename;
        if (File.Exists(filePath))
        {
            //反序列化过程
            //创建一个二进制格式化程序
            BinaryFormatter bf = new BinaryFormatter();
            //打开一个文件流
            FileStream fileStream = File.Open(filePath, FileMode.Open);
            //调用格式化程序的反序列化方法，将文件流转换为一个Save对象
            SaveObject save = (SaveObject)bf.Deserialize(fileStream);
            //关闭文件流
            fileStream.Close();

            return save;

        }
        return default(SaveObject);
    }

    //JSON:存档和读档
    public static void SaveByJson<JsonObject>(string dataPath,string filename,JsonObject saveObject)
    {
        string filePath = dataPath + "/dataFile/" + filename;
        //利用JsonMapper将jsonObject对象转换为Json格式的字符串
        string saveJsonStr = JsonMapper.ToJson(saveObject);
        //进行压缩加密
        saveJsonStr = ZipHelper.GZipCompressString(saveJsonStr);
        //将这个字符串写入到文件中
        //创建一个StreamWriter，并将字符串写入文件中
        StreamWriter sw = new StreamWriter(filePath);
        sw.Write(saveJsonStr);
        //关闭StreamWriter
        sw.Close();
    }

    public static SaveObject LoadByJson<SaveObject>(string dataPath, string filename)
    {
        string filePath = dataPath + "/dataFile/" + filename;
        if (File.Exists(filePath))
        {
            //创建一个StreamReader，用来读取流
            StreamReader sr = new StreamReader(filePath);
            //将读取到的流赋值给jsonStr
            string jsonStr = sr.ReadToEnd();
            //关闭
            sr.Close();
            //解压
            jsonStr = ZipHelper.GZipDecompressString(jsonStr);
            //将字符串jsonStr转换为Save对象
            SaveObject saveObject = JsonMapper.ToObject<SaveObject>(jsonStr);
            return saveObject;
        }
        return default(SaveObject);
    }

    public static FileInfo[] GetFiles(string path, string defaultType = "*"){
        if (!Directory.Exists(path))
            throw new FileNotFoundException(string.Format("{0}文件不存在",path));
        DirectoryInfo direction = new DirectoryInfo(path);
        FileInfo[] files = direction.GetFiles(defaultType, SearchOption.AllDirectories);
        return files;
    }
    #endregion
    public static bool CompareObject(object obj1,object obj2){
        var _obj1 = Md5(LitJson.JsonMapper.ToJson(obj1));
        var _obj2 = Md5(LitJson.JsonMapper.ToJson(obj2));
        return _obj1 == _obj2;
    }
    /// <summary>
    /// 获得一个范围内的随机值
    /// </summary>
    /// <param name="valStr">格式：1-2或1%-2%</param>
    /// <returns></returns>
    public static object GetRandVal(string valStr){
        var symbol = "";
        var tempStr = valStr;
        if(tempStr.IndexOf('%') > 0) {
            tempStr = tempStr.Replace("%","");
            symbol = "%";
        }
        var valArr = tempStr.Split('-');
        if(valArr.Length != 2) return valStr;
        Random rand = new Random();
        return rand.Next(int.Parse(valArr[0]),int.Parse(valArr[1]) + 1) + symbol;
    }
    /// <summary>
    /// 把obj1转为T类型，数据结构得一样
    /// </summary>
    /// <param name="obj1"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static T ConverToType<T>(object obj1){
        var objJson = JsonMapper.ToJson(obj1);
        return JsonMapper.ToObject<T>(objJson);
    }
    /// <summary>
    /// 获取当前程序集 
    /// </summary>
    /// <returns></returns>
    public static Assembly GetCurAssembly(){
        return Assembly.GetExecutingAssembly();
    }
}
